//
//  KongWAreaViewController.m
//  LoveOfPet
//
//  Created by dllo on 15/11/14.
//  Copyright © 2015年 孔维. All rights reserved.
//

#import "KongWAreaViewController.h"
#import "DataAnalysis.h"
#import "KongWAreaModel.h"
#import "CoreDatamanager.h"
#import "Citys.h"
@interface KongWAreaViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (retain, nonatomic) NSMutableArray *cityArray;

@property (retain, nonatomic) UITableView *tableView;

@property (retain, nonatomic) NSMutableArray *modelArray;

@property (retain, nonatomic) NSMutableArray *kindOfCity;

@property (retain, nonatomic) NSMutableArray *titleArray;

@property (nonatomic, retain) CoreDatamanager *coreDatamanager;
@property (nonatomic, retain) NSArray *resultArray;
@property (nonatomic, assign) BOOL b;
@end

@implementation KongWAreaViewController
-(void)dealloc
{
    [_modelArray release];
    [_tableView release];
    [_cityArray release];
    [_kindOfCity release];
    [_titleArray release];
    [_coreDatamanager release];
    [_resultArray release];
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated{

    self.coreDatamanager = [CoreDatamanager shareManager];
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Citys"];
    self.resultArray = [_coreDatamanager.managedObjectContext executeFetchRequest:request error:nil];
    [request release];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = NO;
    self.title = @"城市选择";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:20 * kWidth],NSForegroundColorAttributeName:[UIColor colorWithRed:0.952 green:1.000 blue:0.967 alpha:1.000]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 40 *kWidth, 40 *kHeight);
    [backBtn setImage:[UIImage imageNamed:@"ms_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtn) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.modelArray = [NSMutableArray array];
    self.kindOfCity = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    [self loadData];
    [self creatTableView];
    
}

-(void)loadData
{
    NSString *urlString = @"http://api.5ichong.com/app.php/common/get_cities_with_hostipal";
   [DataAnalysis dataAnalysisGETWithUrlString:urlString parameters:nil showHuD:YES hiddenView:nil successfulBlock:^(id responseObject) {
        NSDictionary *dic = responseObject;
        self.cityArray = [dic objectForKey:@"data"];
        for (NSDictionary *dic in self.cityArray) {
            KongWAreaModel *areaModel = [KongWAreaModel areaWithDictionary:dic];
            [self.modelArray addObject:areaModel];
        }
        [self dataHandle];
        [self.tableView reloadData];
       
   }failureBlock:^(NSError *error) {
       
   }];
    
}
//把首字母相同的地区存到一起
-(void)dataHandle
{
    for (int i = 0; i < self.modelArray.count; i ++) {
        KongWAreaModel *iModel = self.modelArray[i];
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObject:iModel];
        for (int j = i + 1; j < self.modelArray.count; j ++) {
            KongWAreaModel *jModel = self.modelArray[j];
            if ([iModel.city_letter isEqualToString:jModel.city_letter]) {
                [tempArray addObject:jModel];
                [self.modelArray removeObjectAtIndex:j];
                j = j -1;
            }
        }
        [self.kindOfCity addObject:tempArray];
    }
    
    for (NSArray *array in self.kindOfCity) {
        [self.titleArray addObject:((KongWAreaModel *)[array objectAtIndex:0]).city_letter];
    }

}

-(void)creatTableView
{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - kHeight * 64) style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"areaCellIndentify"];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return [[self.kindOfCity objectAtIndex:section] count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.kindOfCity.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30 *kHeight;
}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return ((KongWAreaModel *)[[self.kindOfCity objectAtIndex:section] objectAtIndex:0] ).city_letter;
}

//设置索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
    return self.titleArray;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50 *kHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"areaCellIndentify"];
    cell.textLabel.text = ((KongWAreaModel *)[[self.kindOfCity objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).city_name;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@", ((KongWAreaModel *)[[self.kindOfCity objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).city_name);
    
    for (Citys *city in _resultArray) {
        if ([city.cityName isEqualToString:((KongWAreaModel *)[[self.kindOfCity objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).city_name]) {
            self.b = YES;
            break;
        }
    }
    if (self.b != YES) {
        Citys *city = [NSEntityDescription insertNewObjectForEntityForName:@"Citys" inManagedObjectContext:_coreDatamanager.managedObjectContext];
        city.cityName = ((KongWAreaModel *)[[self.kindOfCity objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).city_name;
        [_coreDatamanager saveContext];
        

    }
   
    self.hidesBottomBarWhenPushed = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)backBtn
{    self.hidesBottomBarWhenPushed = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
